<?php

namespace App\Console\Commands;

use App\Models\Article;
use App\Models\SiteDomain;
use App\Service\Email;
use Illuminate\Console\Command;

class MakeWord extends Command
{
    /**
     * 请求：
     *  php artisan command:make-word
     *  sudo -u www php /www/wwwroot/option/artisan command:make-word
     *
     */
    /**
     * 参数与选项的区别
     *      在执行命令时，参数必须严格按定义时的顺序输入，不需输入参数名，只需输入参数的值即可。
     *      输入选项则必须带选项名，且选项名前须加 -- 前缀（选项简写字母前加 -），选项可按任意顺序输入
     */

    // 请求 以及参数
    // protected $signature = 'command:name {param1} {param2}';  // 必填参数
    // protected $signature = 'command:name {参数名?} {参数名=默认值} {参数名? : 参数说明}';  // 可选参数
    // protected $signature = 'command:name {--选项名} {--选项名=} {--选项名=默认值} {--简写字母|选项名} {--选项名 : 选项说明}';  // 选项
    protected $signature   = 'command:make-word {date?}';
    protected $description = '每天生成word，可以每天定时生成，也可以由页面请求生成';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // 获取时间：昨天的时间
        $yesDay = $this->argument('date');
        if(empty($yesDay)){
            $yesDay    = date('Y-m-d', strtotime("-1 days"));
        }

        // 因为这几天没有数据，所以固定某一天的数据
        //$yesDay    = "2024-3-4";
        $beginTime = strtotime($yesDay);
        $endTime   = strtotime($yesDay) + 86400 - 1;

        // 获取数据
        $lists = (new Article())->getArticleInTime($beginTime, $endTime);
        $lists = array_values($lists);

        // word的参数
        $path     = app()->basePath().'/public/';
        $wordFile = $path.'易见舆情日报.docx';
        $newfile  = $path.'date/易见舆情日报'.$yesDay.'.docx';  // 新文件名

        //此处替换word文档中的对应变量值
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);
        $processor->setValue('date', $yesDay);
        /*$processor->setValue('JIDCode', '测试');
        $processor->setValue('JLegalRepresentative', '测试');*/

        /**
         * *** word的内容
         * ${block_name2}
         * ${thTitle}（${thAuthor}）
         * ${thDescription}
         * 链接：${thUrl}
         * ${/block_name2}
         */
        // 如果是循环数据
        /*$list    = $this->data();
        $replace = [];
        foreach($list as $item){
            $descripte = str_repeat($item['description'], rand(100, 300));
            $htmlLink  = "<a href='".$item['link']."'>".$item['link']."</a>";
            $htmlLink  = $item['link'];
            $replace[] = ['thTitle' => $item['title'], 'thAuthor' => $item['author'], 'thDescription' => $descripte, 'thUrl' => $htmlLink];
        }
        $processor->cloneBlock('block_name2', 0, true, false, $replace);*/

        /**
         * *** word的内容
         * ${block_name}
         * Customer: ${customer_name}
         * Address: ${customer_address}
         * ${/block_name}
         * // 循环操作
         * $replace = array(
         *   array('customer_name' => 'Batman', 'customer_address' => 'Gotham City'),
         *   array('customer_name' => 'Superman', 'customer_address' => 'Metropolis'),
         * );
         * $processor->cloneBlock('block_name', 0, true, false, $replace);
         **/
        /*$replace = [];
        foreach($lists as $item){
            $sitename = $item['site']['name'];
            $within   = [];
            foreach($item['news'] as $_new){
                $row = [
                    'sitename'    => $sitename,
                    'description' => $_new['description'],
                    'from_url'    => $_new['from_url'],
                    'title'       => "<a href='".$_new['from_url']."'>".$_new['title']."</a>",
                    'author'      => $_new['author'],
                    'push_time'   => date("Y-m-d H:i", $_new['push_time']),
                ];
                // 整理
                $within[] = $row;
            }
            $replace[] = ['sitename' => $sitename,];
            $processor->cloneBlock('block_within', 0, true, false, $within);
        }
        $processor->cloneBlock('block_name', 0, true, false, $replace);*/
        // 复制多份 并在字段后面添加 #1 的字样
        $processor->cloneBlock('block_name', count($lists), true, true);
        $replace = [];
        foreach($lists as $key => $item){
            $rowNumber = $key + 1;
            $sitename  = $item['site']['name'];
            $processor->setValue("sitename#{$rowNumber}", $sitename);
            $processor->setValue("block_within#{$rowNumber}", '${block_within_'.$rowNumber.'}');
            $processor->setValue("{/block_within#{$rowNumber}}", '{/block_within_'.$rowNumber.'}');

            $html = new \PhpOffice\PhpWord\Shared\Html();
            // 替换
            $within = [];
            foreach($item['news'] as $_new){
                $row = [
                    "ar_sitename#{$rowNumber}"    => $sitename,
                    "ar_description#{$rowNumber}" => $_new['description'],
                    "ar_from_url#{$rowNumber}"    => $_new['from_url'],
                    "ar_author#{$rowNumber}"      => $_new['author'],
                    "ar_push_time#{$rowNumber}"   => date("Y-m-d H:i", $_new['push_time']),
                    //"ar_title#{$rowNumber}"       => "<w:hyperlink Address=''".$_new['from_url']."'>".$_new['title']."</w:hyperlink>",
                    //"ar_title#{$rowNumber}"       => '<w:r><w:instrText xml:space="preserve" w:hyperlink="'.$_new['from_url'].'">'.$_new['title'].'</w:instrText></w:r>',

                    // <w:instrText xml:space="preserve" w:hyperlink="'.$_new['from_url'].'" ></w:instrText>
                   "ar_title#{$rowNumber}"       => '<w:r><w:rPr><w:hyperlink w:val="'.$_new['from_url'].'"/><w:rFonts w:hint="eastAsia" w:ascii="微软雅黑" w:hAnsi="微软雅黑" w:eastAsia="微软雅黑" w:cs="微软雅黑"/><w:color w:val="0000FF"/><w:u w:val="single"/></w:rPr><w:t>'.$_new['title'].'</w:t></w:r>',
                    //"ar_title#{$rowNumber}"       => $_new['title'],
                ];
                // 整理
                $within[] = $row;
            }
            //$replace[$rowNumber]=$within;
            $processor->cloneBlock("block_within_{$rowNumber}", 0, true, false, $within);
        }

        //保存word  存放位置可以自定义
        $processor->saveAs($newfile);

        /*// 重新替换循环
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($newfile);
        foreach($replace as $rowNumber => $_within){
            $processor->cloneBlock("block_within_{$rowNumber}", 0, true, false, $_within);
        }

        //保存word  存放位置可以自定义
        $processor->saveAs($newfile);*/

        $this->line('生成word成功！');
    }


    // 参数与选项
    public function _handle()
    {
        // 参数
        echo $text = $this->argument('text');
        echo chr(10);
        $all = $this->argument();
        var_dump($all);
        echo chr(10);

        // 选项
        $option = $this->option('show');
        echo $option;
        echo chr(10);


        echo '测试';
        $this->info("md5('{测试}') = 测试");   // 输出

        return 0;
    }

}
